/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.standardcloud.security.sso.config;

import com.alibaba.fastjson.JSONObject;
import com.hyts.standardcloud.security.sso.filter.UsernamePasswordAuthenticationFilter;
import com.hyts.standardcloud.security.sso.service.UserSSOService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @project-name:standard-cloud
 * @package-name:com.hyts.standardcloud.security.sso
 * @author:LiBo/Alex
 * @create-date:2020-04-26 10:11
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
//@EnableWebSecurity//启动Spring Security的安全管理
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     * 该bean的作用是，在UserDetailsService接口的loadUserByUsername返回的UserDetail中包含了
     * password, 该bean就将用户从页面提交过来的密码进行处理，处理之后与UserDetail中密码进行比较。
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 用户sso单点登录服务对象
     * @return
     */
    @Bean
    public UserSSOService userSSOService(){
        return new UserSSOService();
    }

    // 统一安全配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 意思是将图片验证码过滤器，加载用户名密码验证过滤器之前
        http
                //.exceptionHandling()
//                authenticationEntryPoint(
//                (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)->{
//                    if(isAjaxRequest(request)){
//                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,authException.getMessage());
//                        JSONObject result = new JSONObject();
//                        result.put("code",500);
//                        result.put("msg","用户未认证");
//                        response.setContentType("application/json;charset=utf-8");
//                        response.getWriter().println(result);
//                        response.getWriter().flush();
//                        response.getWriter().close();
//                    }else{
//                        response.sendRedirect("/login");
//                    }
//                })
                //.and().
                .formLogin()//使用form进行登录
                //指定登录页面
                .loginPage("/login")
                //表示form往哪里进行提交
                .loginProcessingUrl("/authentication/login")
//                .successHandler((HttpServletRequest var1, HttpServletResponse var2, Authentication var3)->{
//                    JSONObject result = new JSONObject();
//                    result.put("code",200);
//                    var2.setContentType("application/json;charset=utf-8");
//                    var2.getWriter().println(result);
//                    var2.getWriter().flush();
//                    var2.getWriter().close();
//                })
//                .failureHandler((HttpServletRequest var1, HttpServletResponse var2, AuthenticationException var3)->{
//                    JSONObject result = new JSONObject();
//                    result.put("code",500);
//                    result.put("msg",var3.getMessage());
//                    var2.setContentType("application/json;charset=utf-8");
//                    var2.getWriter().println(result);
//                    var2.getWriter().flush();
//                    var2.getWriter().close();
//                })
                .and()
                .authorizeRequests()
                .antMatchers("/authentication/login","/login",
                                "/login-sso.html", "/images/**","/js/**",
                                "/css/**","favicon.ico","logo.png")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
                //.logout()
                //.logoutUrl("/login");
                //.addFilter(new UsernamePasswordAuthenticationFilter())
    }

    // 密码加密处理
    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        System.out.println(bCryptPasswordEncoder.encode("1"));
    }

//    @Override
//    @Bean
//    public AuthenticationManager authenticationManager() throws Exception {
//        return (Authentication authentication)->{
//            String userName = (String) authentication.getPrincipal();
//            String password = (String) authentication.getCredentials();
//            return authentication;
//        };
//    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}
